﻿using DevExpress.ExpressApp;
using DevExpress.ExpressApp.DC;
using DevExpress.ExpressApp.Model;
using DevExpress.ExpressApp.Model.Core;
using System.Collections.Concurrent;
using System.Reflection;

namespace EasyXaf.BlazorTabbedMdi;

[DomainLogic(typeof(IModelViewMdi))]
public class ModelViewMdiDomainLogic
{
    public static IEnumerable<Type> Get_MdiWindowTemplateTypes(IModelView view)
    {
        if (view is ModelNode node)
        {
            var typesInfo = node.CreatorInstance.TypesInfo;
            var typeToTypeInfoCacheField = typeof(TypesInfo).GetField("typeToTypeInfoCache", BindingFlags.NonPublic | BindingFlags.Instance);
            var typeToTypeInfoCache = (ConcurrentDictionary<Type, DevExpress.ExpressApp.DC.TypeInfo>)typeToTypeInfoCacheField.GetValue(typesInfo);
            var argumentTypes = new Type[] { typeof(Window) };
            return typeToTypeInfoCache.Keys
                .Where(t => typeof(MdiViewWindowTemplate).IsAssignableFrom(t))
                .Where(t => t != typeof(MdiMainWindowTemplate))
                .Where(t => t.IsClass && t.IsVisible && !t.IsAbstract)
                .Where(t => !t.IsGenericType && !t.IsGenericTypeDefinition)
                .Where(t => t.GetConstructor(argumentTypes) != null)
                .ToList();
        }
        return Array.Empty<Type>();
    }
}
